// 游戏数据总线
class DataBus {
  constructor() {
    this.reset();
  }

  reset() {
    this.score = 0;
    this.level = 1;
    this.lives = 3;
    this.gameOver = false;
    this.bullets = [];
    this.planes = [];
    this.bombs = [];
    this.lastPlaneSpawn = 0;
    this.lastBombSpawn = 0;
    this.planeSpawnInterval = 2000;
    this.bombSpawnInterval = 1500;
  }
}

// 游戏精灵基类
class Sprite {
  constructor(x = 0, y = 0, width = 0, height = 0) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.visible = true;
  }

  update() {}
  render(ctx) {}
}

// 坦克类
class Tank extends Sprite {
  constructor() {
    super(0, 0, 60, 40);
    this.speed = 300;
  }

  update(dt) {
    // 坦克位置通过点击事件直接更新
  }

  render(ctx) {
    if (!this.visible) return;
    
    // 坦克主体
    ctx.fillStyle = '#27ae60';
    ctx.fillRect(this.x, this.y, this.width, this.height);
    
    // 坦克履带
    ctx.fillStyle = '#2c3e50';
    ctx.fillRect(this.x - 5, this.y + 5, 10, 30);
    ctx.fillRect(this.x + this.width - 5, this.y + 5, 10, 30);
    
    // 坦克炮管
    ctx.fillStyle = '#34495e';
    ctx.fillRect(this.x + this.width/2 - 3, this.y - 15, 6, 20);
    
    // 坦克高光
    ctx.fillStyle = 'rgba(255,255,255,0.3)';
    ctx.fillRect(this.x + 2, this.y + 2, this.width - 4, 8);
  }

  init(worldWidth, worldHeight) {
    this.x = worldWidth / 2 - this.width / 2;
    this.y = worldHeight - this.height - 20;
    this.visible = true;
  }
}

// 子弹类
class Bullet extends Sprite {
  constructor(x, y) {
    super(x, y, 4, 12);
    this.speed = 500;
  }

  update(dt) {
    this.y -= this.speed * dt;
    if (this.y < -this.height) {
      this.visible = false;
    }
  }

  render(ctx) {
    if (!this.visible) return;
    ctx.fillStyle = '#f39c12';
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
}

// 飞机类
class Plane extends Sprite {
  constructor(x, y) {
    super(x, y, 50, 30);
    this.speed = 100 + Math.random() * 50;
  }

  update(dt, worldHeight) {
    this.y += this.speed * dt;
    if (this.y > worldHeight + 800) {
      this.visible = false;
    }
  }

  render(ctx) {
    if (!this.visible) return;
    ctx.fillStyle = '#e74c3c';
    ctx.fillRect(this.x, this.y, this.width, this.height);
    // 飞机细节
    ctx.fillStyle = '#c0392b';
    ctx.fillRect(this.x + 5, this.y + 5, 40, 20);
    ctx.fillStyle = '#95a5a6';
    ctx.fillRect(this.x + 15, this.y + 10, 20, 10);
  }
}

// 炸弹类
class Bomb extends Sprite {
  constructor(x, y) {
    super(x, y, 12, 12);
    this.speed = 200 + Math.random() * 100;
  }

  update(dt, worldHeight) {
    this.y += this.speed * dt;
    if (this.y > worldHeight + 800) {
      this.visible = false;
    }
  }

  render(ctx) {
    if (!this.visible) return;
    ctx.fillStyle = '#2c3e50';
    ctx.beginPath();
    ctx.arc(this.x + this.width/2, this.y + this.height/2, this.width/2, 0, Math.PI * 2);
    ctx.fill();
    ctx.fillStyle = '#e74c3c';
    ctx.beginPath();
    ctx.arc(this.x + this.width/2, this.y + this.height/2, this.width/3, 0, Math.PI * 2);
    ctx.fill();
  }
}

// 主游戏类
class Main {
  constructor() {
    this.canvas = null;
    this.ctx = null;
    this.aniId = 0;
    this.worldWidth = 375;
    this.worldHeight = 667;
    this.dpr = 1;
    
    this.databus = new DataBus();
    this.tank = new Tank();
  }

  init(canvas, ctx) {
    this.canvas = canvas;
    this.ctx = ctx;
    
    // 设置画布尺寸
    const sys = wx.getSystemInfoSync();
    this.dpr = Math.max(1, sys.pixelRatio || 1);
    
    // 确保canvas尺寸正确设置
    if (canvas.width && canvas.height) {
      this.worldWidth = canvas.width / this.dpr;
      this.worldHeight = canvas.height / this.dpr;
    } else {
      // 如果canvas尺寸未设置，使用默认值
      this.worldWidth = 375;
      this.worldHeight = 667;
    }
    
    // 初始化坦克
    this.tank.init(this.worldWidth, this.worldHeight);
    
    // 开始游戏循环
    this.start();
  }

  start() {
    this.databus.reset();
    this.tank.init(this.worldWidth, this.worldHeight);
    this.aniId = 0;
    this.loop();
  }

  loop() {
    this.update();
    this.render();
    this.aniId = setTimeout(() => {
      this.loop();
    }, 16); // 约60FPS
  }

  update() {
    const now = Date.now();
    const dt = Math.min(0.033, (now - (this.databus.lastTs || now)) / 1000 || 0.016);
    this.databus.lastTs = now;

    // 生成飞机
    if (now - this.databus.lastPlaneSpawn > this.databus.planeSpawnInterval) {
      this.spawnPlane();
      this.databus.lastPlaneSpawn = now;
    }

    // 生成炸弹
    if (now - this.databus.lastBombSpawn > this.databus.bombSpawnInterval) {
      this.spawnBomb();
      this.databus.lastBombSpawn = now;
    }

    // 更新游戏对象
    this.tank.update(dt);
    this.databus.bullets.forEach(bullet => bullet.update(dt));
    this.databus.planes.forEach(plane => plane.update(dt, this.worldHeight));
    this.databus.bombs.forEach(bomb => bomb.update(dt, this.worldHeight));

    // 清理无效对象
    this.databus.bullets = this.databus.bullets.filter(bullet => bullet.visible);
    this.databus.planes = this.databus.planes.filter(plane => plane.visible);
    this.databus.bombs = this.databus.bombs.filter(bomb => bomb.visible);

    // 碰撞检测
    this.collisionDetection();
  }

  render() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

    // 绘制背景
    this.drawBackground();
    
    // 绘制游戏对象
    this.tank.render(this.ctx);
    this.databus.bullets.forEach(bullet => bullet.render(this.ctx));
    this.databus.planes.forEach(plane => plane.render(this.ctx));
    this.databus.bombs.forEach(bomb => bomb.render(this.ctx));
  }

  drawBackground() {
    const ctx = this.ctx;
    const w = this.worldWidth;
    const h = this.worldHeight;
    
    // 渐变背景
    const gradient = ctx.createLinearGradient(0, 0, 0, h);
    gradient.addColorStop(0, '#34495e');
    gradient.addColorStop(1, '#2c3e50');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, w, h);

    // 星星背景
    ctx.globalAlpha = 0.6;
    ctx.fillStyle = '#ecf0f1';
    for (let i = 0; i < 30; i++) {
      const x = (i * 97.3) % (w + 40) - 20;
      const y = (i * 61.7) % (h);
      ctx.fillRect(x, y, 2, 2);
    }
    ctx.globalAlpha = 1;
  }

  spawnPlane() {
    const x = Math.random() * (this.worldWidth - 50);
    this.databus.planes.push(new Plane(x, -50));
  }

  spawnBomb() {
    if (this.databus.planes.length === 0) return;
    const randomPlane = this.databus.planes[Math.floor(Math.random() * this.databus.planes.length)];
    this.databus.bombs.push(new Bomb(
      randomPlane.x + randomPlane.width/2 - 6,
      randomPlane.y + randomPlane.height
    ));
  }

  collisionDetection() {
    // 坦克与炸弹碰撞
    for (let i = this.databus.bombs.length - 1; i >= 0; i--) {
      const bomb = this.databus.bombs[i];
      if (this.checkCollision(this.tank, bomb)) {
        this.databus.bombs.splice(i, 1);
        this.databus.lives--;
        if (this.databus.lives <= 0) {
          this.gameOver();
          return;
        }
      }
    }

    // 子弹与飞机碰撞
    for (let i = this.databus.bullets.length - 1; i >= 0; i--) {
      const bullet = this.databus.bullets[i];
      for (let j = this.databus.planes.length - 1; j >= 0; j--) {
        const plane = this.databus.planes[j];
        if (this.checkCollision(bullet, plane)) {
          this.databus.bullets.splice(i, 1);
          this.databus.planes.splice(j, 1);
          this.databus.score += 10;
          this.updateLevel();
          break;
        }
      }
    }
  }

  checkCollision(rect1, rect2) {
    return rect1.x < rect2.x + rect2.width &&
           rect1.x + rect1.width > rect2.x &&
           rect1.y < rect2.y + rect2.height &&
           rect1.y + rect1.height > rect2.y;
  }

  updateLevel() {
    const nextLevelScore = this.databus.level * 50;
    if (this.databus.score >= nextLevelScore) {
      this.databus.level += 1;
      this.databus.planeSpawnInterval = Math.max(500, this.databus.planeSpawnInterval - 200);
      this.databus.bombSpawnInterval = Math.max(800, this.databus.bombSpawnInterval - 150);
    }
  }

  gameOver() {
    this.databus.gameOver = true;
    const best = wx.getStorageSync('tank_best_score') || 0;
    if (this.databus.score > best) {
      wx.setStorageSync('tank_best_score', String(this.databus.score));
    }
  }

  // 坦克移动方法
  moveTankLeft() {
    if (this.databus.gameOver) return;
    const newX = Math.max(0, this.tank.x - 30);
    this.tank.x = newX;
    wx.vibrateShort();
  }

  moveTankRight() {
    if (this.databus.gameOver) return;
    const newX = Math.min(this.worldWidth - this.tank.width, this.tank.x + 30);
    this.tank.x = newX;
    wx.vibrateShort();
  }

  fire() {
    if (this.databus.gameOver) return;
    const bullet = new Bullet(
      this.tank.x + this.tank.width/2 - 2,
      this.tank.y - 15
    );
    this.databus.bullets.push(bullet);
  }
}

// 页面逻辑
Page({
  data: {
    score: 0,
    level: 1,
    lives: 3,
    best: 0,
    gameOver: false
  },

  onLoad() {
    this.main = new Main();
    this._initGame();
  },

  onShow() {
    if (this.main && this.main.canvas) {
      this.main.start();
    }
  },

  onHide() {
    if (this.main) {
      if (this.main.aniId) {
        clearTimeout(this.main.aniId);
      }
      this.main.aniId = 0;
    }
  },

  onResize() {
    if (this.main && this.main.canvas) {
      this._resizeCanvas();
    }
  },

  onShareAppMessage() {
    return {
      title: `我在坦克打飞机拿到 ${this.data.score} 分，来挑战！`
    };
  },

  async _initGame() {
    const best = wx.getStorageSync('tank_best_score') || 0;
    this.setData({ best });

    const query = wx.createSelectorQuery();
    query.select('#game').fields({ node: true, size: true }).exec((res) => {
      const canvas = res && res[0] && res[0].node;
      if (!canvas) return;
      
      const ctx = canvas.getContext('2d');
      
      // 设置canvas尺寸
      const sys = wx.getSystemInfoSync();
      const dpr = Math.max(1, sys.pixelRatio || 1);
      const size = res[0];
      canvas.width = Math.round(size.width * dpr);
      canvas.height = Math.round(size.height * dpr);
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      
      this.main.init(canvas, ctx);
      
      // 更新数据
      this.updateData();
    });
  },

  _resizeCanvas() {
    const query = wx.createSelectorQuery();
    query.select('#game').fields({ size: true }).exec((res) => {
      const size = res && res[0];
      if (!size || !this.main.canvas) return;
      
      const { width, height } = size;
      this.main.canvas.width = Math.round(width * this.main.dpr);
      this.main.canvas.height = Math.round(height * this.main.dpr);
      this.main.ctx.setTransform(this.main.dpr, 0, 0, this.main.dpr, 0, 0);
      this.main.worldWidth = width;
      this.main.worldHeight = height;
    });
  },

  updateData() {
    if (!this.main) return;
    
    this.setData({
      score: this.main.databus.score,
      level: this.main.databus.level,
      lives: this.main.databus.lives,
      gameOver: this.main.databus.gameOver
    });

    // 持续更新数据
    setTimeout(() => {
      this.updateData();
    }, 100);
  },

  onRestart() {
    if (this.main) {
      this.main.start();
      this.updateData();
    }
  },

  onFire() {
    if (this.main) {
      this.main.fire();
    }
  },

  onLeftTap() {
    console.log('左移点击');
    if (this.main) {
      this.main.moveTankLeft();
    }
  },

  onRightTap() {
    console.log('右移点击');
    if (this.main) {
      this.main.moveTankRight();
    }
  }
});
